//
//  NSString+RichText.m
//  string
//
//  Created by  on 16/9/8.
//  Copyright © 2016年 . All rights reserved.
//

#import "NSString+RichText.h"


@implementation NSString (RichText)

+ (NSString *)sendPCText:(NSString *)text {
    return [NSString stringWithFormat:@"<span>%@</span>",text];
}


+ (NSString *)filterHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        [scanner scanUpToString:@"<" intoString:nil];
        [scanner scanUpToString:@">" intoString:&text];
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    return html;
}


+ (NSString *)richText:(NSString *)text {
    
    NSMutableString *muText = [NSMutableString stringWithString:text];
    
    NSString *spanStart = @"<SPAN>";
    NSString *spanEnd = @"</SPAN>";
    //    NSString *imgName = @"emotion\emotion.cry.gif";
   
    // 字符串处理
    NSString *pattern = @"\\【[a-zA-Z0-9\\u4e00-\\u9fa5]+\\】";
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
    NSArray *allReusults =   [regular matchesInString:muText options:NSMatchingReportCompletion range:NSMakeRange(0, text.length)];

    for (NSInteger i =  allReusults.count - 1 ; i >= 0; --i) {
        
        NSTextCheckingResult *result = allReusults[i];
        
        NSString *emotionName = [text substringWithRange:result.range];
        
        
        NSBundle *bundle = [NSBundle bundleForClass:[NSString class]];
        NSString *bundlePath = [bundle pathForResource:@"PlayerSDK.bundle" ofType:nil];
        
        NSString *plist_path = [bundlePath stringByAppendingPathComponent:@"text2key.plist"];
        
        NSDictionary *picDict = [[NSDictionary alloc] initWithContentsOfFile:plist_path];
        NSString *imageName = [picDict valueForKey:emotionName];
        
        NSString *imgSrc = [NSString stringWithFormat:@"<IMG src=\"%@\" custom=\"false\">",imageName];
        
        [muText replaceCharactersInRange:result.range withString:imgSrc];
        
    
    }
    
    NSString *rich = muText.copy;
    
    NSString *htmlRich = [[spanStart stringByAppendingString:rich] stringByAppendingString:spanEnd];
    
    //替换之后显示
    return htmlRich;
}





@end
